import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {} // 不能设置为null，否则会读取不到属性，产生报错
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, result) {
      state.userInfo = result
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(context, data) {
      const res = await login(data)
      context.commit('setToken', res)
      setTimeStamp() // 设置时间戳(用于检测token过期时间)
    },
    async getUserInfo(context) {
      const res = await getUserInfo()
      const baseInfo = await getUserDetailById(res.userId)
      context.commit('setUserInfo', { ...res, ...baseInfo })
      return res
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
      resetRouter() // 重置路由
      // 加了命名空间namespaced之后的context不再是全局的，只能访问子模块的mutation
      // 通过第三个参数{ root: true }来使用根级的context
      context.commit('permission/setRoutes', [], { root: true })
    }
  }
}
